import Vue from 'vue';

module.exports = {
  // 判断是 IOS 还是安卓
  getPhoneType() {
    var type = 'other'
    switch (uni.getSystemInfoSync().platform) {
      case 'android':
        type = 'android'
        break;
      case 'ios':
        type = 'ios'
        break;
      default:
        break;
    }
    return type
  },

  // 处理手机号码中间四位
  phoneNumHide(phone) {
    var reg = /^(\d{3})\d{4}(\d{4})$/;
    phone = phone.replace(reg, "$1****$2");
    return phone
  },

  // 处理文件路径
  getLocalFilePath(path) {
    if (path.indexOf('_www') === 0 || path.indexOf('_doc') === 0 || path.indexOf('_documents') === 0 || path.indexOf('_downloads') === 0) {
      return path
    }
    if (path.indexOf('file://') === 0) {
      return path
    }
    if (path.indexOf('/storage/emulated/0/') === 0) {
      return path
    }
    if (path.indexOf('/') === 0) {
      var localFilePath = plus.io.convertAbsoluteFileSystem(path)
      if (localFilePath !== path) {
        return localFilePath
      } else {
        path = path.substr(1)
      }
    }
    return '_www/' + path
  },

  // 图片转 base64ToPath
  pathToBase64(path) {
    let that = this
    return new Promise((resolve, reject) => {
      if (typeof window === 'object' && 'document' in window) {
        if (typeof FileReader === 'function') {
          var xhr = new XMLHttpRequest()
          xhr.open('GET', path, true)
          xhr.responseType = 'blob'
          xhr.onload = () => {
            if (this.status === 200) {
              let fileReader = new FileReader()
              fileReader.onload = (e) => {
                resolve(e.target.result)
              }
              fileReader.onerror = reject
              fileReader.readAsDataURL(this.response)
            }
          }
          xhr.onerror = reject
          xhr.send()
          return
        }
        var canvas = document.createElement('canvas')
        var c2x = canvas.getContext('2d')
        var img = new Image
        img.onload = () => {
          canvas.width = img.width
          canvas.height = img.height
          c2x.drawImage(img, 0, 0)
          resolve(canvas.toDataURL())
          canvas.height = canvas.width = 0
        }
        img.onerror = reject
        img.src = path
        return
      }
      if (typeof plus === 'object') {
        plus.io.resolveLocalFileSystemURL(that.getLocalFilePath(path), (entry) => {
          entry.file((file) => {
            var fileReader = new plus.io.FileReader()
            fileReader.onload = (data) => {
              resolve(data.target.result)
            }
            fileReader.onerror = (error) => {
              reject(error)
            }
            fileReader.readAsDataURL(file)
          }, (error) => {
            reject(error)
          })
        }, (error) => {
          reject(error)
        })
        return
      }
      if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
        wx.getFileSystemManager().readFile({
          filePath: path,
          encoding: 'base64',
          success(res) {
            resolve('data:image/png;base64,' + res.data)
          },
          fail(error) {
            reject(error)
          }
        })
        return
      }
      reject(new Error('not support'))
    })
  },

  // base 64 转文件路径
  base64ToPath(base64) {
    return new Promise((resolve, reject) => {
      if (typeof window === 'object' && 'document' in window) {
        base64 = base64.split(',')
        var type = base64[0].match(/:(.*?);/)[1]
        var str = atob(base64[1])
        var n = str.length
        var array = new Uint8Array(n)
        while (n--) {
          array[n] = str.charCodeAt(n)
        }
        return resolve((window.URL || window.webkitURL).createObjectURL(new Blob([array], {
          type: type
        })))
      }
      var extName = base64.match(/data\:\S+\/(\S+);/)
      if (extName) {
        extName = extName[1]
      } else {
        reject(new Error('base64 error'))
      }
      var fileName = Date.now() + '.' + extName
      if (typeof plus === 'object') {
        var bitmap = new plus.nativeObj.Bitmap('bitmap' + Date.now())
        bitmap.loadBase64Data(base64, () => {
          var filePath = '_doc/uniapp_temp/' + fileName
          bitmap.save(filePath, {}, () => {
            bitmap.clear()
            resolve(filePath)
          }, (error) => {
            bitmap.clear()
            reject(error)
          })
        }, (error) => {
          bitmap.clear()
          reject(error)
        })
        return
      }
      if (typeof wx === 'object' && wx.canIUse('getFileSystemManager')) {
        var filePath = wx.env.USER_DATA_PATH + '/' + fileName
        wx.getFileSystemManager().writeFile({
          filePath: filePath,
          data: base64.replace(/^data:\S+\/\S+;base64,/, ''),
          encoding: 'base64',
          success() {
            resolve(filePath)
          },
          fail(error) {
            reject(error)
          }
        })
        return
      }
      reject(new Error('not support'))
    })
  },

  // 打开第三方地图应用
  toMapAPP(latitude, longitude, name) {
    let url = "";
    if (plus.os.name == "Android") { // 判断是安卓端
      plus.nativeUI.actionSheet({ // 选择菜单
        title: "选择地图应用",
        cancel: "取消",
        buttons: [{
          title: "腾讯地图"
        }, {
          title: "百度地图"
        }, {
          title: "高德地图"
        }]
      }, (e) => {
        switch (e.index) {
          // 下面是拼接 url,不同系统以及不同地图都有不同的拼接字段
          case 1:
            // 注意 referer=xxx 的 xxx 替换成你在腾讯地图开发平台申请的 key
            url = `qqmap://map/geocoder?coord=${latitude},${longitude}&referer=7ZDBZ-POOWJ-3PRFG-KCBCD-WAH5K-AVFVL`;
            break;
          case 2:
            url =
              `baidumap://map/marker?location=${latitude},${longitude}&title=${name}&coord_type=gcj02&src=andr.baidu.openAPIdemo`;
            break;
          case 3:
            url = `androidamap://viewMap?sourceApplication=appname&poiname=${name}&lat=${latitude}&lon=${longitude}&dev=0`;
            break;
          default:
            break;
        }
        if (url != "") {
          url = encodeURI(url);
          // plus.runtime.openURL(url, (e) => {}) // 调起手机APP应用
          plus.runtime.openURL(url, (e) => {
            plus.nativeUI.alert("本机未安装指定的地图应用");
          });
        }
      })
    } else {
      // iOS上获取本机是否安装了百度高德地图，需要在 manifest 里配置
      // 在 manifest.json 文件 app-plus -> distribute -> apple -> urlschemewhitelist 点下添加
      // （如urlschemewhitelist:["iosamap","baidumap","qqmap"]）  
      plus.nativeUI.actionSheet({
        title: "选择地图应用",
        cancel: "取消",
        buttons: [{
          title: "腾讯地图"
        }, {
          title: "百度地图"
        }, {
          title: "高德地图"
        }]
      }, (e) => {
        switch (e.index) {
          case 1:
            url = `qqmap://map/geocoder?coord=${latitude},${longitude}&referer=xxx`;
            break;
          case 2:
            url =
              `baidumap://map/marker?location=${latitude},${longitude}&title=${name}&content=${name}&src=ios.baidu.openAPIdemo&coord_type=gcj02`;
            break;
          case 3:
            url =
              `iosamap://viewMap?sourceApplication=applicationName&poiname=${name}&lat=${latitude}&lon=${longitude}&dev=0`;
            break;
          default:
            break;
        }
        if (url != "") {
          url = encodeURI(url);
          plus.runtime.openURL(url, (e) => {
            plus.nativeUI.alert("本机未安装指定的地图应用");
          });
        }
      })
    }
  },

  // 获取页面路径
  getCurPage() {
    var pages = getCurrentPages();
    var page = pages[pages.length - 1]
    return 'https://czjxmx.com/h5/#' + page.route
  },

  // 短震动
  vibrate() {
    let UIImpactFeedbackGenerator = plus.ios.importClass('UIImpactFeedbackGenerator');
    let impact = new UIImpactFeedbackGenerator();
    impact.prepare();
    impact.init(1);
    impact.impactOccurred();
  },

  // 获取用户cid
  getUserCid() {
    let clientInfo = plus.push.getClientInfo()
    return clientInfo.clientid // 设备CID
  },

  // 数组内是否包含
  inArray(search, array) {
    for (var i in array) {
      if (array[i] == search) {
        return true;
      }
    }
    return false;
  },

  // 公众号登录鉴权--静默授权
  gzhLoginBase(url, type) {
    // type  :  snsapi_base 静默授权  snsapi_userinfo 获取用户信息
    let local = encodeURIComponent(url) // 获取当前页面地址
    let Appid = '你的APPID'
    window.location.href =
      "https://open.weixin.qq.com/connect/oauth2/authorize?appid=" +
      Appid + // 你APP申请的APPId，每个app都有个ID是识别你app的方式
      "&redirect_uri=" +
      local +
      "&response_type=code&scope=" + type + "&state=1#wechat_redirect";
  },

  // 判断是否是微信浏览器
  is_wx() {
    let en = window.navigator.userAgent.toLowerCase()
    // 匹配en中是否含有 MicroMessenger 字符串
    if (en.match(/MicroMessenger/i) == 'micromessenger') {
      return true
    }
    if (en.match(/MicroMessenger/i) != 'micromessenger') {
      return false
    }
  },

  // 随机整数
  random(lower, upper) {
    return Math.floor(Math.random() * (upper - lower + 1)) + lower;
  },

  // 监听网络
  onNetWork() {
	  let net_type = 'none';
    let func = (res) => {
      if (res.networkType === 'none') {
        uni.showToast({
          title: '网络异常或不通',
          icon: 'error',
          duration: 3000
        });
      }else{
		  net_type = res.networkType;
	  }
    }
    uni.getNetworkType({
      success: func
    });
    uni.onNetworkStatusChange(func);
	 return net_type;
  },

  // 数组置顶
  toFirst(arr, index) {
    if (index != 0) {
      arr.unshift(arr.splice(index, 1)[0]);
    }
    return arr;
  },

  // 判断地址是否包含前缀
  httpLink(url) {
    const Http = url.substr(0, 7).toLowerCase()
    const Https = url.substr(0, 8).toLowerCase()
    if (Http === "http://" || Https === "https://") {
      return true
    }
    return false
  },

  // 获取当前页面路由---包含参数
  getNowPagePath() {
    let routes = getCurrentPages(); // 获取当前打开过的页面路由数组
    if (routes.length == 0) {
      return '/index/index'
    }
    let curRoute = routes[routes.length - 1].route // 获取当前页面路由
    let curParam = routes[routes.length - 1].options; // 获取路由参数
    // 拼接参数
    let param = ''
    for (let key in curParam) {
      if (key != 'code') {
        if (param == '') {
          param += '?' + key + '=' + curParam[key]
        } else {
          param += '&' + key + '=' + curParam[key]
        }
      }
    }

    let page_url = '/' + curRoute + param
    return page_url
  },

  // 获取字符长度   中文2个字符，英文一个字符
  strlen(str) {
    var len = 0;
    for (var i = 0; i < str.length; i++) {
      var c = str.charCodeAt(i);
      // 单字节加1   
      if ((c >= 0x0001 && c <= 0x007e) || (0xff60 <= c && c <= 0xff9f)) {
        len++
      } else {
        len += 2
      }
    }
    return len
  },

  // 字符空格过滤
  trim(str) {
    return str.replace(/^(\s|\u00A0)+/, '').replace(/(\s|\u00A0)+$/, '');
  },
  
  //过滤反斜杆
  rpXiegan(str){
	  if(str!=undefined&&JSON.stringify(str)!='null'&&JSON.stringify(str)!=''){
		  let newstr = str.toString().replace(/\\/g, "");
		  newstr = str.toString().replace(/"/g, "”");//去掉双引号
		  return newstr
	  }else{
		  return
	  }
  },
  
  // 数字转中文
  toChinesNum(num) {
    let changeNum = ['零', '一', '二', '三', '四', '五', '六', '七', '八', '九'];
    let unit = ["", "十", "百", "千", "万"];
    num = parseInt(num);
    let getWan = (temp) => {
      let strArr = temp.toString().split("").reverse();
      let newNum = "";
      for (var i = 0; i < strArr.length; i++) {
        newNum = (i == 0 && strArr[i] == 0 ? "" : (i > 0 && strArr[i] == 0 && strArr[i - 1] == 0 ? "" : changeNum[strArr[i]] + (strArr[i] == 0 ? unit[0] : unit[i]))) + newNum;
      }
      return newNum;
    }
    let overWan = Math.floor(num / 10000);
    let noWan = num % 10000;
    if (noWan.toString().length < 4) {
      noWan = "0" + noWan;
    }
    return overWan ? getWan(overWan) + "万" + getWan(noWan) : getWan(num);
  },
  
  /**
   * 时间戳转化为年 月 日 时 分 秒
   * number: 传入时间戳
   * format：返回格式，支持自定义，但参数必须与formateArr里保持一致
   */
  formatTime(number, format) {
  	var formateArr = ['Y', 'M', 'D', 'h', 'm', 's'];
  	var returnArr = [];
   
  	var date = new Date(number * 1000);
  	returnArr.push(date.getFullYear());
  	returnArr.push(formatNumber(date.getMonth() + 1));
  	returnArr.push(formatNumber(date.getDate()));
   
  	returnArr.push(formatNumber(date.getHours()));
  	returnArr.push(formatNumber(date.getMinutes()));
  	returnArr.push(formatNumber(date.getSeconds()));
   
  	for (var i in returnArr) {
  		format = format.replace(formateArr[i], returnArr[i]);
  	}
   
  	return format;
  },
  //设置cookie
  setCookie: function (cname, cvalue, exdays) {
  	var d = new Date();
  	d.setTime(d.getTime() + (exdays * 24 * 60 * 60 * 1000));
  	var expires = "expires=" + d.toUTCString();
  	document.cookie = cname + "=" + cvalue + "; " + expires;
  	console.info(document.cookie);
  },
  //获取cookie
  getCookie: function (cname) {
  	var name = cname + "=";
  	var ca = document.cookie.split(';');
  	for (var i = 0; i < ca.length; i++) {
  		var c = ca[i];
  		while (c.charAt(0) == ' ') c = c.substring(1);
  		if (c.indexOf(name) != -1) return c.substring(name.length, c.length);
  	}
  	return "";
  },
  //清除cookie
  clearCookie: function (cname) {
  	this.setCookie(cname, "", -1);
  },
  
  // 获取当天日期
  getDateTime: function (type,form='Y-m-d') {
      // 获取当前日期
      let timestamp = Date.parse(new Date());
      let date = new Date(timestamp);
      if (type == 'tomorrow') { // 明天
          date.setDate(date.getDate() + 1);
  
      } else if (type == 'today') { // 今天
          date.setDate(date.getDate());
      }else if(type == 'todaytime'){
		  var currentDateTime = new Date();
		  
		  var year = currentDateTime.getFullYear(); // 获取当前年份
		  var month = currentDateTime.getMonth() + 1; // 获取当前月份（注意，返回的月份范围是 0-11，所以要加 1）
		  var day = currentDateTime.getDate(); // 获取当前日期
		  var hours = currentDateTime.getHours(); // 获取当前小时
		  var minutes = currentDateTime.getMinutes(); // 获取当前分钟
		  var seconds = currentDateTime.getSeconds(); // 获取当前秒数
		  if(month<10){
			  month = '0'+month 
		  }
		  if(day<10){
			  day = '0'+day 
		  }
		  if(hours<10){
			  hours = '0'+hours 
		  }
		  if(minutes<10){
			  minutes = '0'+minutes 
		  }
		  if(seconds<10){
			  seconds = '0'+seconds 
		  }
		  // 格式化输出
		  return year + '-' + month + '-' + day + ' ' + hours + ':' + minutes + ':' + seconds
	  }
      //获取年份  
      var Y = date.getFullYear();
      //获取月份  
      var M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
      //获取当日日期 
      var D = date.getDate() < 10 ? '0' + date.getDate() : date.getDate();
	  let todayDate = '';
	  if(form=='Y-m-d'){
		  todayDate = Y + '-' + M + '-' + D;
	  }else{
		  todayDate = Y + '' + M + '' + D;
	  }
      return todayDate
  },
  /* 
  数组去重
  */
 uniqueArr:function (arr){
        var brr = [];
        for( var i=0; i<arr.length;i++){
            if(brr.indexOf( arr[i]) == -1){
                brr.push( arr[i] );
            }
        }
        return brr
  },
  queryStringify(obj) {
  	let res = []
  	for (let k in obj) {
  		res.push(`${k}=${obj[k]}`)
  	}
  	return res.join('&')
  },
  getQuery(querystring) {
  	let arr = querystring.split('?');
  	querystring = arr[arr.length - 1];
  	arr = querystring.split('&');
  	let result = {};
  	arr.forEach((item, index) => {
  		let v = item.split('=');
  		result[v[0]] = v[1];
  	})
  	console.log(result)
  	return result;
  },
  /* 
  设置顶部导航标题
  */
 setBarTitle:function(title=''){
	 let username = uni.getStorageSync('username')
	 if(username=='admin'){
		 uni.setNavigationBarTitle({
		 	title:title
		 })
	 }else{
		 //更新标题
		 let user = uni.getStorageSync('user') 
		 if(title==''){
			 title = user.username
			 if(user.nickname!=undefined){
				 title = user.nickname
			 }
		 }
		 
		 uni.setNavigationBarTitle({
		 	title:title+"("+user.stock_name+")"
		 })
	 }
 },
 /* 
 单据类型
 */
getOrderTypeName(order_type=0){
	let type_arr = [
		'收货',//0收货
		'源单上架',//1入库上架
		'领料出库',//2出库
		'源单领料出库',//3领料出库
		//"采购退货",//4,
		//"领料退货",//5
		"产品入库",//4
		"销售出库", //5
		"","","","",
		'其他入库',//11其他入库
		'其他出库',//12其他出库
		'盘点',//13盘点
		'采购退回',//14 不引源单
		"领料退货",//15 不引源单
		"调拨", //16调拨
		"直接上架", //17直接上架
		"直接领料",  //18直接领料
		"组装单" //19
	]
	
	//Object.keys(type_arr) 返回的是键值，字符串
	if(Object.keys(type_arr).includes(order_type.toString())){
		return type_arr[order_type]
	}else{
		return ""
	}
},
// 使用reduce()方法将具有相同id的对象的value属性值相加
//二维，key是键值
arraySameKeySum(array = [],key = 'row_id',value = 'real_quantity'){
	//console.log(array)
	const result = array.reduce((accumulator, current) => {
	  const index = accumulator.findIndex(item => item[key] === current[key]);
	  if (index !== -1) {
	    accumulator[index][value] += parseFloat(current[value]);
	  } else {
		  let temp = {}
		  temp[key] = current[key]
		  temp[value] = parseFloat(current[value]);
	      accumulator.push(temp);
	  }
	  return accumulator;
	}, []);
	return result
},
//判断数组内，有无同样物料，同样的货架，出货
//return array、string boolean
checkSameShelvesInvOut(array = [],rtn = 'array',type = ''){
	let boolean = false
	let string = ''
	const result = array.reduce((accumulator, current) => {
		let index = 0
		if(type=='kc_number'){
			//判断同一库存记录，不同直接上架明细，会不会超过库存数
			index = accumulator.findIndex(item => item.b_remark!=''&& item.b_remark == current.kc_id&&item.inv_number == current.inv_number );
		}else{
			index = accumulator.findIndex(item => item.shelves_id == current.shelves_id&&item.inv_number == current.inv_number );
		}
	  
	  if (index !== -1) {
	    accumulator[index]['nums'] ++;
		
		//累计数量
		if(current.fqty!=undefined){
			accumulator[index]['fqtys'] += parseFloat(current.fqty)
		}
		
		boolean = true
		string = current.shelves_name+','+current.inv_name+',存在重复记录'
	  } else {
	      accumulator.push({
			  'shelves_id':current.shelves_id,
			  'shelves_name':current.shelves_name,
			  'inv_number':current.inv_number,
			  'inv_name':current.inv_name,
			  'fqtys':current.fqty == undefined?0:parseFloat(current.fqty),
			  'nums':1,
			  'kc_id':current.b_remark == undefined?'':current.b_remark
		  });
	  }
	  return accumulator;
	}, []);
	
	if(rtn == 'array'){
		return result
	}else if(rtn == 'string'){
		return string
	}else if(rtn == 'boolean'){
		return boolean
	}
},
//选择存货后，转换键值，在show-material-list 显示
setMaterial(inventory = [],arrays = []){
	if(JSON.stringify(inventory) == '{}' || JSON.stringify(inventory) == '[]'){
		return Promise.reject('接收物料参数错误')
	}
	
	//转换键值，很多地方用到
	inventory.real_quantity = 0
	inventory['inv_name'] = inventory.name
	inventory['inv_number'] = inventory.number
	inventory['inv_specification'] = inventory.specification
	inventory['inv_attributes'] = inventory.attributes //暂无用到
	inventory['unit_name'] = inventory.unit
	
	inventory['inv_unit'] = inventory.unit_name
	inventory['inv_unit_code'] = inventory.unit_code
	
	inventory['shelves_id'] = 0
	inventory['shelves_name'] = ''
	arrays.push(inventory)
	return Promise.resolve(arrays)
},
//强制小数后x位
decimalPattern(value){
	if(value == ''||value == undefined){
		return 0
	}
	const qtyDecimal = Vue.prototype.globalData.qtyDecimal
	if(qtyDecimal>0){
		const regexString = `^\\d+(\\.\\d{0,${qtyDecimal}})?$`;
		const regex = new RegExp(regexString);
		if (!regex.test(value)) {
			// 如果输入不符合要求，将输入值重置为符合要求的值
			//this.val = parseFloat(value).toFixed(this.decimalPattern)
			//const decimalPart = roundedNumber.substring(roundedNumber.indexOf('.') + 1, roundedNumber.indexOf('.') + 3);
			//const result = roundedNumber.substring(0, roundedNumber.indexOf('.') + 1) + decimalPart;
			//this.val = result
			value = parseFloat(value).toFixed(qtyDecimal)
		}
	}
	return Number(value)
},
//自定义各种跳转
navTo(type = 'bill' ,param = {}){
	const str = this.queryStringify(param)
	switch(type){
		case 'bill':
		  uni.navigateTo({
		  	url: '/pages/stockbill/list?order_type='+param.order_type
		  })
		break;
		case 'plan':
		  uni.navigateTo({
		  	url: '/pages/instock/plan?'+str //flag=back&process=shouhuo
		  })
		break;
		case 'appmaterial':
		  uni.navigateTo({
		  	url: '/pages/outstock/appmaterial?'+str //flag=back&process=shouhuo
		  })
		break;
		
	}
},
//过滤备注特殊字符
htmlEncode(str) {
 str = str.replace(/\s+/ig, '');
 str = str.replace(/&/g, '');
 str = str.replace(/</g, '');
 str = str.replace(/>/g, '');
 //str = str.replace(/(?:t| |v|r)*n/g, '<br />');
 //str = str.replace(/t/g, '&nbsp; &nbsp; ');
 //str = str.replace(/x22/g, '&quot;');
 //str = str.replace(/x27/g, '&#39;');
 str = str.replace(/"/g, "");
 return str;
},
//获取仓库名
getStockNameByStockID(stock_id){
	let stockhouse_arr = uni.getStorageSync('stockhouse_arr')
	let stock_name = ''
	if(stockhouse_arr!=''){
		let stock = stockhouse_arr.find(ele => ele.id == stock_id)
			if(stock!=undefined){
				//存在
				stock_name = stock.name
			}
	}
	return stock_name
},
//清空本机所有缓存
clearStorageSync(){
	uni.showToast({
		icon:'success',
		title:'清除成功',
		duration:2000
	})
	uni.clearStorageSync()
	setTimeout(()=>{
		uni.reLaunch({
			url:'/pages/index/login',
			success() {
				//关闭其他页面，直接到登录页
				plus.navigator.closeSplashscreen()}
		})
	},1000)
},
//获取设备唯一标识
getDeviceInfo(){
	plus.device.getInfo({
		success:function(e){
			var uuid = uni.getStorageSync('uuid');
			if(uuid==''){
				uni.setStorageSync('uuid',e.imei);//e.uuid
			}
		}
	});
},
//判断权限
checkUserAuth(url = ''){
	let user = uni.getStorageSync('user');
	let msg = ''
	if(user.rules==undefined){
		msg = '请先在WMS平台配置权限'
	}else if(user.rules.length==0){
		msg = '请先在WMS平台配置权限'
	}else{
		if(!this.inArray(url,user.rules)){
			msg = '暂无权限'
		}
	}
	
	if(msg){
		uni.showToast({
			icon:'error',
			title:msg.toString(),
			duration:2000
		})
		return false
	}
	return true
}
}